var Pop = function() {
	var _popup;
	var SELECTOR = {
		'icon' : '[data-icon]',
		'scroll' : '[data-scroll="true"]',
		'toggle' : '.toggle',
		'range' : '[data-rangeinput]',
		'progress' : '[data-progress]',
		'count' : '[data-count]',
		'checkbox' : '[data-checkbox]'
	}

	/**
	 * 自身与子集相结合
	 */
	var _getMatchElements = function($el, selector) {
		return $el.find(selector).add($el.filter(selector));
	}

	/**
	 * 初始化容器内组件
	 * 
	 * @param {String}
	 *            父元素的css选择器
	 * @param {Object}
	 *            父元素或者父元素的zepto实例
	 */
	var init = function(selector) {

		var $el = $(selector || 'body');
		if ($el.length == 0)
			return;

		$.map(_getMatchElements($el, SELECTOR.icon), _init_icon);

		$el = null;
	}
	/**
	 * 构造icon组件
	 */
	var _init_icon = function(el) {
		var $el = $(el), $icon = $el.children('i.icon'), icon = $el.data('icon');
		if ($icon.length > 0) { // 已经初始化，就更新icon
			$icon.attr('class', 'icon ' + icon);
		} else {
			$el.prepend('<i class="icon ' + icon + '"></i>');
		}
	}

	var anim = function(el, animName, duration, ease, callback) {
		var d, e, c;
		var len = arguments.length;
		for (var i = 2; i < len; i++) {
			var a = arguments[i];
			var t = $.type(a);
			t == 'number' ? (d = a) : (t == 'string' ? (e = a) : (t == 'function') ? (c = a) : null);
		}
		$(el).animate(animName, d || J.settings.transitionTime, e || J.settings.transitionTimingFunc, c);
	}
	var J = {
		settings : {
			// page默认动画效果
			transitionType : 'slide',
			// 自定义动画时的默认动画时间(非page转场动画时间)
			transitionTime : 250,
			// 自定义动画时的默认动画函数(非page转场动画函数)
			transitionTimingFunc : "linear",
			// toast 持续时间,默认为3s
			toastDuration : 3000
		}
	};

	var POSITION = {
		'top' : {
			top : 0,
			left : 0,
			right : 0
		},
		'top-second' : {
			top : '44px',
			left : 0,
			right : 0
		},
		'center' : {
			top : '50%',
			left : '5%',
			right : '5%',
			'border-radius' : '3px'
		},
		'bottom' : {
			bottom : 0,
			left : 0,
			right : 0
		},
		'bottom-second' : {
			bottom : '51px',
			left : 0,
			right : 0
		}
	}, ANIM = {
		top : [ 'slideDownIn', 'slideUpOut' ],
		bottom : [ 'slideUpIn', 'slideDownOut' ],
		defaultAnim : [ 'bounceIn', 'bounceOut' ]
	}, TEMPLATE = {
		alert : '<div class="popup-title">{title}</div><div class="popup-content">{content}</div><div id="popup_btn_container"><a data-target="closePopup" data-icon="checkmark">{ok}</a></div>',
		confirm : '<div class="popup-title">{title}</div><div class="popup-content">{content}</div><div id="popup_btn_container"><a data-icon="checkmark">{ok}</a><a class="cancel" data-icon="close">{cancel}</a></div>',
		loading : '<i class="icon spinner"></i><p>{title}</p>'
	};

	var _init = function() {
		$('body').append('<div id="jingle_popup"></div><div id="jingle_popup_mask"></div>');
		_mask = $('#jingle_popup_mask');
		_popup = $('#jingle_popup');
		_subscribeEvents();
	}

	var show = function(options) {
		var settings = {
			height : undefined, // 高度
			width : undefined, // 宽度
			opacity : 0.3, // 透明度
			url : null, // 远程加载url
			tplId : null, // 加载模板ID
			tplData : null, // 模板数据，配合tplId使用
			html : '', // popup内容
			pos : 'center', // 位置 {@String
							// top|top-second|center|bottom|bottom-second}
							// {@object css样式}
			clickMask2Close : true, // 是否点击外层遮罩关闭popup
			showCloseBtn : true, // 是否显示关闭按钮
			arrowDirection : undefined, // popover的箭头指向
			animation : true, // 是否显示动画
			timingFunc : 'linear',
			duration : 200, // 动画执行时间
			onShow : undefined
		// @event 在popup内容加载完毕，动画开始前触发
		}
		$.extend(settings, options);
		clickMask2close = settings.clickMask2Close;
		_mask.css('opacity', settings.opacity);
		// rest position and class
		_popup.attr({
			'style' : '',
			'class' : ''
		});
		settings.width && _popup.width(settings.width);
		settings.height && _popup.height(settings.height);
		var pos_type = $.type(settings.pos);
		if (pos_type == 'object') { // style
			_popup.css(settings.pos);
			transition = ANIM['defaultAnim'];
		} else if (pos_type == 'string') {
			if (POSITION[settings.pos]) { // 已经默认的样式
				_popup.css(POSITION[settings.pos])
				var trans_key = settings.pos.indexOf('top') > -1 ? 'top' : (settings.pos.indexOf('bottom') > -1 ? 'bottom' : 'defaultAnim');
				transition = ANIM[trans_key];
			} else { // pos 为 class
				_popup.addClass(settings.pos);
				transition = ANIM['defaultAnim'];
			}
		} else {
			console.error('错误的参数！');
			return;
		}
		_mask.show();
		var html;
		if (settings.html) {
			html = settings.html;
		} else if (settings.tplId) { // 加载模板
			html = template(settings.tplId, settings.tplData)
		}

		// 是否显示关闭按钮
		if (settings.showCloseBtn) {
			html += '<div id="tag_close_popup" data-target="closePopup" class="icon cancel-circle"></div>';
		}
		// popover 箭头方向
		if (settings.arrowDirection) {
			_popup.addClass('arrow ' + settings.arrowDirection);
			_popup.css('padding', '8px');
			if (settings.arrowDirection == 'top' || settings.arrowDirection == 'bottom') {
				transition = ANIM[settings.arrowDirection];
			}
		}

		_popup.html(html).show();
		init(_popup);
		// 执行onShow事件，可以动态添加内容
		settings.onShow && settings.onShow.call(_popup);

		// 显示获取容器高度，调整至垂直居中
		if (settings.pos == 'center') {
			var height = _popup.height();
			_popup.css('margin-top', '-' + height / 2 + 'px')
		}
		if (settings.animation) {
			anim(_popup, transition[0], settings.duration, settings.timingFunc);
		}
		// J.hasPopupOpen = true;
	}

	/**
	 * 关闭弹出框
	 * 
	 * @param noTransition
	 *            立即关闭，无动画
	 */
	var hide = function(noTransition) {

		if (transition && !noTransition) {
			anim(_popup, transition[1], 200, function() {
				_popup.hide();
				// J.hasPopupOpen = false;
			});
		} else {
			_popup.hide();
			// J.hasPopupOpen = false;
		}
		_mask.hide();
	}
	var _subscribeEvents = function() {
		_mask.on('click', function() {
			clickMask2close && hide();
		});
		_popup.on('click', '[data-target="closePopup"]', function() {
			hide();
		});
	}

	/**
	 * alert组件
	 * 
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 */
	window.alert = function(title, content, btnName) {
		if (!content) {
			content = title;
			title = "提示";
		}
		var markup = TEMPLATE.alert.replace('{title}', title).replace('{content}', content).replace('{ok}', btnName || '确定');
		show({
			html : markup,
			pos : 'center',
			clickMask2Close : false,
			showCloseBtn : false
		});
	}

	/**
	 * confirm 组件
	 * 
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 * @param okCall
	 *            确定按钮handler
	 * @param cancelCall
	 *            取消按钮handler
	 */
	window.confirm = function(title, content, okCall, cancelCall) {
		if (!content) {
			content = title;
			title = "提示";
		}
		var markup = TEMPLATE.confirm.replace('{title}', title).replace('{content}', content).replace('{cancel}', '取消').replace('{ok}', '确定');
		show({
			html : markup,
			pos : 'center',
			clickMask2Close : false,
			showCloseBtn : false
		});
		$('#popup_btn_container [data-icon="checkmark"]').click(function() {
			hide();
			okCall.call(this);
		});
		$('#popup_btn_container [data-icon="close"]').click(function() {
			hide();
			cancelCall.call(this);
		});
	}

	_init();
}();
